import mongoose, { Schema, Document } from 'mongoose';

/**
 * 权限接口定义
 */
export interface IPermission extends Document {
  name: string; // 权限名称，如 'alerts:read', 'tickets:create'
  resource: string; // 资源类型
  action: string; // 操作类型
  description?: string;
  category: string; // 权限分类：system, organization, team
  isSystem: boolean; // 是否是系统级权限
  metadata?: {
    scope?: string;
    conditions?: any;
  };
  createdAt: Date;
  updatedAt: Date;
}

/**
 * 权限 Schema
 */
const PermissionSchema = new Schema<IPermission>(
  {
    name: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      match: [/^[a-z0-9_:]+$/, 'Permission name can only contain lowercase letters, numbers, underscores and colons']
    },
    resource: {
      type: String,
      required: true,
      trim: true,
      enum: [
        'alerts',
        'tickets',
        'knowledge',
        'analytics',
        'settings',
        'organizations',
        'teams',
        'users',
        'roles',
        'permissions'
      ]
    },
    action: {
      type: String,
      required: true,
      enum: ['create', 'read', 'update', 'delete', 'manage', 'assign', 'approve', 'export']
    },
    description: {
      type: String,
      maxlength: 200
    },
    category: {
      type: String,
      required: true,
      enum: ['system', 'organization', 'team', 'resource'],
      default: 'resource'
    },
    isSystem: {
      type: Boolean,
      default: false
    },
    metadata: {
      scope: String,
      conditions: Schema.Types.Mixed
    }
  },
  {
    timestamps: true
  }
);

// 索引
PermissionSchema.index({ name: 1 });
PermissionSchema.index({ resource: 1, action: 1 });
PermissionSchema.index({ category: 1 });

// 静态方法：初始化系统权限
PermissionSchema.statics.initializeSystemPermissions = async function() {
  const systemPermissions = [
    // 告警权限
    { name: 'alerts:read', resource: 'alerts', action: 'read', category: 'resource', description: '查看告警' },
    { name: 'alerts:create', resource: 'alerts', action: 'create', category: 'resource', description: '创建告警' },
    { name: 'alerts:update', resource: 'alerts', action: 'update', category: 'resource', description: '更新告警' },
    { name: 'alerts:delete', resource: 'alerts', action: 'delete', category: 'resource', description: '删除告警' },

    // 工单权限
    { name: 'tickets:read', resource: 'tickets', action: 'read', category: 'resource', description: '查看工单' },
    { name: 'tickets:create', resource: 'tickets', action: 'create', category: 'resource', description: '创建工单' },
    { name: 'tickets:update', resource: 'tickets', action: 'update', category: 'resource', description: '更新工单' },
    { name: 'tickets:delete', resource: 'tickets', action: 'delete', category: 'resource', description: '删除工单' },
    { name: 'tickets:assign', resource: 'tickets', action: 'assign', category: 'resource', description: '分配工单' },

    // 知识库权限
    { name: 'knowledge:read', resource: 'knowledge', action: 'read', category: 'resource', description: '查看知识库' },
    { name: 'knowledge:create', resource: 'knowledge', action: 'create', category: 'resource', description: '创建文档' },
    { name: 'knowledge:update', resource: 'knowledge', action: 'update', category: 'resource', description: '更新文档' },
    { name: 'knowledge:delete', resource: 'knowledge', action: 'delete', category: 'resource', description: '删除文档' },
    { name: 'knowledge:approve', resource: 'knowledge', action: 'approve', category: 'resource', description: '审核文档' },

    // 分析权限
    { name: 'analytics:read', resource: 'analytics', action: 'read', category: 'resource', description: '查看分析数据' },
    { name: 'analytics:export', resource: 'analytics', action: 'export', category: 'resource', description: '导出分析报告' },

    // 设置权限
    { name: 'settings:read', resource: 'settings', action: 'read', category: 'resource', description: '查看设置' },
    { name: 'settings:update', resource: 'settings', action: 'update', category: 'resource', description: '更新设置' },

    // 组织权限
    { name: 'organizations:read', resource: 'organizations', action: 'read', category: 'organization', description: '查看组织' },
    { name: 'organizations:create', resource: 'organizations', action: 'create', category: 'organization', description: '创建组织', isSystem: true },
    { name: 'organizations:update', resource: 'organizations', action: 'update', category: 'organization', description: '更新组织' },
    { name: 'organizations:delete', resource: 'organizations', action: 'delete', category: 'organization', description: '删除组织', isSystem: true },
    { name: 'organizations:manage', resource: 'organizations', action: 'manage', category: 'organization', description: '管理组织' },

    // 团队权限
    { name: 'teams:read', resource: 'teams', action: 'read', category: 'team', description: '查看团队' },
    { name: 'teams:create', resource: 'teams', action: 'create', category: 'team', description: '创建团队' },
    { name: 'teams:update', resource: 'teams', action: 'update', category: 'team', description: '更新团队' },
    { name: 'teams:delete', resource: 'teams', action: 'delete', category: 'team', description: '删除团队' },
    { name: 'teams:manage', resource: 'teams', action: 'manage', category: 'team', description: '管理团队成员' },

    // 用户权限
    { name: 'users:read', resource: 'users', action: 'read', category: 'organization', description: '查看用户' },
    { name: 'users:create', resource: 'users', action: 'create', category: 'organization', description: '创建用户' },
    { name: 'users:update', resource: 'users', action: 'update', category: 'organization', description: '更新用户' },
    { name: 'users:delete', resource: 'users', action: 'delete', category: 'organization', description: '删除用户' },

    // 角色权限
    { name: 'roles:read', resource: 'roles', action: 'read', category: 'organization', description: '查看角色' },
    { name: 'roles:create', resource: 'roles', action: 'create', category: 'organization', description: '创建角色' },
    { name: 'roles:update', resource: 'roles', action: 'update', category: 'organization', description: '更新角色' },
    { name: 'roles:delete', resource: 'roles', action: 'delete', category: 'organization', description: '删除角色' },
    { name: 'roles:assign', resource: 'roles', action: 'assign', category: 'organization', description: '分配角色' }
  ];

  for (const perm of systemPermissions) {
    await this.findOneAndUpdate(
      { name: perm.name },
      perm,
      { upsert: true, new: true }
    );
  }
};

const Permission = mongoose.model<IPermission>('Permission', PermissionSchema);

export default Permission;
